﻿using System.Text.Json;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using TianlalaHSB.Models;
using TianlalaHSB.Utils;

namespace TianlalaHSB.Views;

/// <summary>
///     MerchantAccountRefundListView.xaml 的交互逻辑
/// </summary>
public partial class MerchantAccountRefundListView : Page
{
    private const int Size = 10;

    private readonly AccountRecordQuery _query = new();
    private Paginate<MerchantAccountRefund> _paginate;

    public MerchantAccountRefundListView()
    {
        InitializeComponent();

        _paginate = new Paginate<MerchantAccountRefund>();

        _query.start = 1;
        DataContext = _query;
    }

    private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        e.Handled = !Number.IsInteger(e.Text);
        if (_paginate.last != 0) e.Handled = int.Parse(e.Text) > _paginate.last;
    }

    private void PrevPage(object sender, RoutedEventArgs e)
    {
        var startVal = Start.Text == "" ? 1 : int.Parse(Start.Text) - 1;
        Start.Text = startVal.ToString();
        SubmitButton_Click(sender, e);
    }

    private void NextPage(object sender, RoutedEventArgs e)
    {
        var startVal = Start.Text == "" ? 1 : int.Parse(Start.Text) + 1;
        Start.Text = startVal.ToString();
        SubmitButton_Click(sender, e);
    }

    private void FirstPage(object sender, RoutedEventArgs e)
    {
        Start.Text = "1";
        SubmitButton_Click(sender, e);
    }

    private void LastPage(object sender, RoutedEventArgs e)
    {
        Start.Text = _paginate.last.ToString();
        SubmitButton_Click(sender, e);
    }

    private async void SubmitButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var startVal = Start.Text.Trim();
            if (string.IsNullOrEmpty(startVal)) throw new Exception("页码不能为空");

            var current = int.Parse(startVal);
            if (current < 1) throw new Exception("页码必须大于0");

            if (_paginate.last != 0 && current > _paginate.last) throw new Exception("已是最后一页");

            // 获取选中日期
            var startDateVal = startDate.SelectedDate.HasValue ? startDate.SelectedDate.Value : endDate.DisplayDate;
            var endDateVal = endDate.SelectedDate.HasValue ? endDate.SelectedDate.Value : endDate.DisplayDate;

            // 准备POST请求的数据 
            var postData = new
            {
                headReqSerialNo = HttpUtil.GetHeadReqSerialNo(),
                startDate = startDateVal.ToString("yyyyMMdd"),
                endDate = endDateVal.ToString("yyyyMMdd"),
                fileFlag = 0,
                start = (current - 1) * Size + 1,
                size = Size
            };

            var responseBody = await HttpUtil.Request("03050103A0032", postData);
            var list = JsonSerializer.Deserialize<ResponseList<MerchantAccountRefund>>(responseBody);
            if (list?.dtos == null || list.dtos.Count == 0) throw new Exception("无数据");

            // 在这里处理获取到的数据，例如更新UI
            RecordListView.ItemsSource = list.dtos;

            _paginate = new Paginate<MerchantAccountRefund>(current, list.total);

            PrevButton.IsEnabled = current != 1;
            FirstButton.IsEnabled = current != 1;
            NextButton.IsEnabled = current != _paginate.last;
            LastButton.IsEnabled = current != _paginate.last;
            LastButton.Content = _paginate.last;
            JumpButton.IsEnabled = _paginate.last != 1;
            PageStackPanel.Visibility = Visibility.Visible;
        }
        catch (Exception ex)
        {
            // 处理异常，例如网络问题或无效的请求等
            MessageBox.Show(ex.Message, "提示", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void ViewButton_Click(object sender, RoutedEventArgs e)
    {
        if (sender is not Button { Tag: MerchantAccountRefund item }) return;

        // 创建并显示详情页
        var detailWindow = new MerchantAccountRefundDetailView(item)
        {
            WindowStartupLocation = WindowStartupLocation.CenterScreen,
            Width = 600,
            Height = 500
        };
        detailWindow.ShowWindow();
    }

    //03050103B0033: 调账
    private void AdjustButton_Click(object sender, RoutedEventArgs e)
    {
        if (sender is not Button { Tag: MerchantAccountRefund item }) return;

        // 创建并显示详情页
        var childWindow = new MerchantAccountTransferView(item)
        {
            WindowStartupLocation = WindowStartupLocation.CenterScreen
        };
        childWindow.ChildWindowClosed += ChildWindow_Closed;
        childWindow.ShowWindow();
    }

    //03050103B0034: 退款
    private void RefundButton_Click(object sender, RoutedEventArgs e)
    {
        if (sender is not Button { Tag: MerchantAccountRefund item }) return;

        // 创建并显示详情页
        var childWindow = new MerchantAccountRefundView(item)
        {
            WindowStartupLocation = WindowStartupLocation.CenterScreen
        };
        childWindow.ChildWindowClosed += ChildWindow_Closed;
        childWindow.ShowWindow();
    }

    private void ChildWindow_Closed(object sender, EventArgs e)
    {
        // 在这里刷新 MainWindow 的内容
        SubmitButton_Click(sender, new RoutedEventArgs());
    }
}